﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlickrNet;
using Bongiozzo.Models;
using System.Collections;
using System.Threading;
using System.Globalization;
using Bongiozzo.Properties;
using System.Web.Script.Serialization;

namespace Bongiozzo.Controllers
{
    public class HomeViewBag 
    {
        public List<FlickrProject> FlickrProjects;
        public Photo CurrentPhoto;
        public string PhotosetId;
        public List<Photo> LastPhotos;
        public IEnumerable<Tweet> Tweets;
        public IEnumerable<Movie> Movies;
        public string Language;
        public int IndexOfCurrentPhoto;
        public string UserName;
        public string FlickrUserID;
        public string KinopoiskUserID;
        public string Email;
        public string fb_app_id;
        public string PhotosJSON;
        public string SiteUrl;
    }

    public class PhotoJSON 
    {
        public string thumb {get; set; }
        public string image {get; set; }
        public string title {get; set; }
        public string description {get; set; }
        public string link {get; set; }
        public string url {get; set; }
    }
    
    public class HomeController : Controller
    {
        public ActionResult setLanguage(string id)
        {
            id = id.ToLower() == "ru" ? "ru" : "en";
            Response.AppendCookie(LocalizationAwareAttribute.createCookie(id));
            return Redirect("/");
        }

        private string getLanguage()
        {
            return Thread.CurrentThread.CurrentUICulture.Name == "ru-RU" ? "ru" : "en";
        }
                
        [LocalizationAware]
        [OutputCache(Duration = 20 * 60, Location = System.Web.UI.OutputCacheLocation.Server, VaryByCustom = "lang")]
        public ActionResult Index()
        {
            HomeViewBag bag = new HomeViewBag();
            bag.UserName = Settings.Default.UserName;
            bag.fb_app_id = Settings.Default.fb_app_id;
            bag.SiteUrl = Settings.Default.SiteURL;

            bag.Language = getLanguage();
            bag.KinopoiskUserID = Settings.Default.KinopoiskId;
            bag.Email = Settings.Default.Email;

            return View(bag);
        }

        [ChildActionOnly]
        [OutputCache(Duration = 10*60*60)]
        public ActionResult GetProjects(string language)
        {
            HomeViewBag bag = new HomeViewBag();
            FlickrContext flickr = new FlickrContext();
            bag.FlickrProjects = flickr.GetProjects(language);
            return View(bag);
        }

        [ChildActionOnly]
        [OutputCache(Duration = 60 * 60)]
        public ActionResult GetLastPhotos(string language)
        {
            HomeViewBag bag = new HomeViewBag();
            FlickrContext flickr = new FlickrContext();
            bag.LastPhotos = flickr.GetLastPhotos(5, language, 1).ToList();
            return View(bag);
        }

        [ChildActionOnly]
        [OutputCache(Duration = 60 * 60)]
        public ActionResult GetTweets()
        {
            HomeViewBag bag = new HomeViewBag();
            bag.UserName = Settings.Default.UserName;
            TwitterModel twitter = new TwitterModel();
            bag.Tweets = twitter.GetTweets(5);
            return View(bag);
        }

        [ChildActionOnly]
        [OutputCache(Duration = 10*60*60)]
        public ActionResult GetMovies()
        {
            HomeViewBag bag = new HomeViewBag();
            KinopoiskModel kinopoisk = new KinopoiskModel();
            bag.Movies = kinopoisk.GetMovies(5);
            return View(bag);
        }

        private string getJSON(List<Photo> list, string p)
        {
            List<PhotoJSON> json = new List<PhotoJSON>();
            foreach (Photo pht in list)
                json.Add(new PhotoJSON
                {
                    thumb = pht.ThumbnailUrl,
                    image = pht.LargeUrl,
                    title = pht.Title,
                    description = !String.IsNullOrEmpty(pht.OriginalFormat) && pht.Title != pht.OriginalFormat ? pht.OriginalFormat : "",
                    link = pht.WebUrl,
                    url = String.IsNullOrEmpty(p) ?
                        Settings.Default.SiteURL + Url.Action("Photo", new { controller = "Home", id = pht.PhotoId }) :
                        Settings.Default.SiteURL + Url.Action("Gallery", new { controller = "Home", id = pht.PhotoId, photoset = p })
                });

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(json);
        }

        
        [LocalizationAware]
        [OutputCache(Duration = 60*60, Location = System.Web.UI.OutputCacheLocation.Server, VaryByCustom = "lang")]
        public ActionResult Gallery(string id, string photoset)
        {
            HomeViewBag bag = new HomeViewBag();
            bag.UserName = Settings.Default.UserName; 
            bag.fb_app_id = Settings.Default.fb_app_id;
            bag.SiteUrl = Settings.Default.SiteURL;
                        
            FlickrContext flickr = new FlickrContext();
            List<Photo> galleryPhotos;
            try
            {
                galleryPhotos = flickr.GetPhotosetPhotos(photoset, getLanguage()).ToList();
            }
            catch {
                Response.StatusCode = 404;
                return null;            
            }
            bag.IndexOfCurrentPhoto = galleryPhotos.FindIndex(delegate(Photo ph) { return ph.PhotoId == id; });
            if (galleryPhotos.Count == 0 || galleryPhotos[0].UserId != Settings.Default.FlickrUserId || bag.IndexOfCurrentPhoto == -1)
            {
                Response.StatusCode = 404;
                return null;            
            }
            bag.CurrentPhoto = galleryPhotos[bag.IndexOfCurrentPhoto]; 
            bag.PhotosetId = photoset;
            bag.PhotosJSON = getJSON(galleryPhotos, bag.PhotosetId);

            return View(bag);
        }

        [LocalizationAware]
        [OutputCache(Duration = 60 * 60, Location = System.Web.UI.OutputCacheLocation.Server, VaryByCustom = "lang")]
        public ActionResult Photo(string id)
        {
            HomeViewBag bag = new HomeViewBag();
            bag.UserName = Settings.Default.UserName;
            bag.fb_app_id = Settings.Default.fb_app_id;
            bag.SiteUrl = Settings.Default.SiteURL;

            string language = getLanguage();

            FlickrContext flickr = new FlickrContext();
            List<Photo> galleryPhotos;
            int page = 0;
            do {
                page++;
                galleryPhotos = flickr.GetLastPhotos(100, language, page).ToList();
                if (galleryPhotos.Count == 0)
                {
                    Response.StatusCode = 404;
                    return null;
                }
                bag.IndexOfCurrentPhoto = galleryPhotos.FindIndex(delegate(Photo ph) { return ph.PhotoId == id; });
            } while (bag.IndexOfCurrentPhoto == -1);
            bag.CurrentPhoto = galleryPhotos[bag.IndexOfCurrentPhoto];
            bag.PhotosJSON = getJSON(galleryPhotos, null);

            return View("Gallery", bag);
        }
    }
}
